<?php

/**
 * Created by PhpStorm.
 * User: freewheel
 * Date: 2016/10/12
 * Time: 17:35
 */
include_once("DB_Operation.php");

$pricePattern = "/^([0-9]*[.]?)?[0-9]{0,2}$/";
$textPattern = "/^[\\w&\\- ]+$/";

class Product_Operation extends DB_Operation
{
    public function operate($conn)
    {

    }

    public function getImageDir()
    {
        return "../images/products/";
    }


    public function getResizedImageDir()
    {
        return "../images/re_products/";
    }
}

class Insert_Product extends Product_Operation
{
    public function operate($conn)
    {
        global $pricePattern,$textPattern;
        if (!isset($_POST['catid'])) {
            throw new InvalidArgumentException("catid parameter is missing!");
        }
        if (!isset($_POST['name'])) {
            throw new InvalidArgumentException("name parameter is missing!");
        }
        if (!isset($_POST['price'])) {
            throw new InvalidArgumentException("price parameter is missing!");
        }
        if (!isset($_POST['description'])) {
            throw new InvalidArgumentException("description parameter is missing!");
        }
        if (!isset($_FILES['image'])) {
            throw new InvalidArgumentException("image parameter is missing!");
        }

        $imageExtension = $this->getImageExtension($this->getImageDir());
        $imageValidateMsg = $this->validate_image($imageExtension);
        if ($imageValidateMsg == "OK") {

            if (!preg_match($pricePattern, $_POST['price'])) {
                throw new InvalidArgumentException("price parameter is invalid!");
            }

            if (!preg_match($textPattern,$_POST['name'])){
                throw new InvalidArgumentException("name parameter is invalid!");
            }

            if (!preg_match($textPattern,$_POST['description'])){
                throw new InvalidArgumentException("description parameter is invalid!");
            }

            $desc = ($_POST['description']);
            $validName = ($_POST['name']);

            $stmt = $conn->prepare("INSERT INTO products (pid, catid, pname,price,description,extension)
    VALUES (NULL,:catid, :name, :price,:description, :extension)");
            $stmt->bindParam(':catid', $_POST['catid']);
            $stmt->bindParam(':name', $validName);
            $stmt->bindParam(':price', $_POST['price']);
            $stmt->bindParam(':description', $desc);
            $stmt->bindParam(':extension', $imageExtension);
            $stmt->execute();
//            echo "Add new product successfully!<br/>";

            $this->upload_image($this->getImageDir(),$this->getResizedImageDir(), 'product' . $conn->lastInsertId() . "." . $imageExtension);
        } else {
            throw new InvalidArgumentException($imageValidateMsg);
        }
    }
}

class Update_Product extends Product_Operation
{
    public function operate($conn)
    {
        global $pricePattern,$textPattern;
        if (empty($_POST['pid'])) {
            throw new InvalidArgumentException("pid is missing");
        }

        if (empty($_POST['catid'])) {
            throw new InvalidArgumentException("catid is missing");
        }

        $update_items = array();

        $update_fields = 'catid = :catid';
        $params = [];

        $params[':pid'] = $_POST['pid'];
        $params[':catid'] = $_POST['catid'];

        if (!empty($_POST['name'])) {
            if (!preg_match($textPattern,$_POST['name'])){
                throw new InvalidArgumentException("name parameter is invalid!");
            }
            $update_fields = $update_fields . ",pname = :name";
            $params[':name'] = ($_POST['name']);
            $update_items['name']= ($_POST['name']);
        }

        if (!empty($_POST['price'])) {
            if (!preg_match($pricePattern, $_POST['price'])) {
                throw new InvalidArgumentException("price parameter is invalid! ");
            }

            $update_fields = $update_fields . ",price = :price";
            $params[':price'] = $_POST['price'];
            $update_items['price'] = $_POST['price'];
        }

        if (!empty($_POST['description'])) {
            if (!preg_match($textPattern,$_POST['description'])){
                throw new InvalidArgumentException("description parameter is invalid!");
            }
            $update_fields = $update_fields . ",description = :description";
            $params[':description'] = ($_POST['description']);
            $update_items['description'] = $_POST['description'];
        }


        $sql = "UPDATE products SET  $update_fields  WHERE pid= :pid";
//        echo $sql . "   ";
//        var_dump($params);
        $stmt = $conn->prepare($sql);
        $stmt->execute($params);

        if (isset($_FILES["image"]) && trim(basename($_FILES["image"]["name"]) ) != "") {
            $imageExtension = $this->getImageExtension($this->getImageDir());
            $imageValidateMsg = $this->validate_image($imageExtension);
            if ($imageValidateMsg == "OK") {
                $stmt = $conn->prepare("UPDATE products SET  extension = :extension  WHERE pid= :pid");
                $stmt->bindParam(':pid', $params[':pid']);
                $stmt->bindParam(':extension', $imageExtension);
                $stmt->execute();

                $this->upload_image($this->getImageDir(),$this->getResizedImageDir(), 'product' . $params[':pid'] . "." . $imageExtension);
                $update_items['image'] = 'product' . $params[':pid'] . "." . $imageExtension;
            } else {
                throw new InvalidArgumentException($imageValidateMsg);
            }
        }

        $stmt = $conn->prepare("Select cname From categories WHERE catid = :catid");
        $stmt->bindParam(':catid', $_POST['catid']);
        $stmt->execute();

        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $category = $stmt->fetch();
        $update_items['cname'] = $category['cname'];

//        echo "Update product successfully!<br/>";
        return $update_items;
    }
}

class Delete_Product extends Product_Operation
{
    public function operate($conn)
    {
        $stmt = $conn->prepare("SELECT extension FROM products  WHERE pid= :pid");
        $stmt->bindParam(':pid', $_POST['pid']);
        $stmt->execute();
        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $product = $stmt->fetch();

        $imageExtension = $product['extension'];
        $this->delete_image($this->getImageDir(), 'product' . $_POST['pid'] . "." . $imageExtension);

        $stmt = $conn->prepare("DELETE  FROM products  WHERE pid= :pid");
        $stmt->bindParam(':pid', $_POST['pid']);

        $stmt->execute();

//        echo "Delete product successfully!<br/>";
    }
}